<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDialog = true">添加角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="list">
        <!-- 放置列 -->
        <el-table-column align="center" width="200" label="角色">
          <template slot-scope="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" />
            <span v-else>
              {{ row.name }}
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="200" label="启用">
          <template slot-scope="{ row }">
            <el-switch
              v-if="row.isEdit"
              v-model="row.editRow.state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
            />
            <span v-else>
              {{ row.state === 1 ? '已启用' : '未启用' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="描述">
          <template slot-scope="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" />
            <span v-else>
              {{ row.description }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="操作"
        >
          <template slot-scope="{ row }">
            <template v-if="row.isEdit">
              <el-button type="text" size="small" @click="editOk(row)">确定</el-button>
              <el-button type="text" size="small" @click="row.isEdit = false">取消</el-button>
            </template>
            <template v-else>
              <el-button type="text" size="small" @click="hAssign(row.id)">分配权限</el-button>
              <el-button type="text" size="small" @click="hEdit(row)">编辑</el-button>
              <!-- <el-button type="text" size="small">删除</el-button> -->
              <template>
                <el-popconfirm
                  confirm-button-text="好的"
                  cancel-button-text="不用了"
                  icon="el-icon-info"
                  icon-color="red"
                  title="这是一段内容确定删除吗？"
                  @onConfirm="del(row.id)"
                >
                  <el-button slot="reference" type="text" size="small">删除</el-button>
                </el-popconfirm>
              </template>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <!-- 放置分页组件 -->
        <el-pagination
          :current-page="page"
          background
          :page-sizes="[1,2,3,4,5,6,7,8,9,10]"
          layout="prev, pager, next, sizes"
          :total="total"
          :page-size="pagesize"
          @current-change="hPagination"
          @size-change="hSizeChange"
        />
      </el-row>
    </div>
    <el-dialog width="500px" title="新增角色" :visible.sync="showDialog" @close="hCancel">
      <!-- 表单内容 -->
      <el-form ref="form" label-width="120px" :model="form" :rules="rules">
        <el-form-item prop="name" label="角色名称">
          <el-input v-model="form.name" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item label="启用">
          <el-switch
            v-model="form.state"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item prop="description" label="角色描述">
          <el-input v-model="form.description" type="textarea" :rows="3" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="addAffirm">确定</el-button>
              <el-button size="mini" @click="hCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分配权限 -->
    <assign-permission ref="refAssign" :assign-id="assignId" :is-assign.sync="isAssign" />
  </div>
</template>
<script>
import { addRole, getRole, updateEdit, delRole } from '@/api/role'
import { Message } from 'element-ui'
import assignPermission from './components/assignPermission.vue'
export default {
  name: 'Role',
  components: {
    assignPermission
  },
  data() {
    return {
      list: [],
      // 总条数
      total: 0,
      // 页码
      page: 1,
      // 每页多少条数据
      pagesize: 5,
      // 新增和编辑的弹出框
      showDialog: false,
      // 分配权限
      isAssign: false,
      assignId: 0,
      form: {
        name: '',
        state: 0,
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getRole()
  },
  methods: {
    // 分配权限
    hAssign(id) {
      // 打开弹窗
      this.isAssign = true
      this.assignId = id
      // 调用子组件方法
      this.$nextTick(() => {
        this.$refs.refAssign.getExisting()
      })
    },
    // 角色列表数据
    async getRole() {
      // 发请求获取数据
      const res = await getRole({ page: this.page, pagesize: this.pagesize })
      // console.log(res)
      this.list = res.data.rows
      // 给每一行都补充一个属性, isEdit 用来标记当前行是否处于编辑状态
      this.list.forEach(item => {
        // this.$set(对象, 新添加的属性名, 属性值)
        // 这样补充的属性是响应式的 ===> 改变了值, 视图也会跟着变化
        this.$set(item, 'isEdit', false)
        // 做数据缓存
        this.$set(item, 'editRow', {
          id: item.id,
          name: item.name,
          description: item.description,
          state: item.state
        })
      })
      // 总条数
      this.total = res.data.total
    },
    // 页码
    hPagination(page) {
      // 更改页码
      this.page = page
      // 重新发请求
      this.getRole()
    },
    // 每页条数
    hSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      // 更新每页显示的条数
      this.pagesize = val
      // 更新之后跳转到第一页
      this.page = 1
      // 重新发请求
      this.getRole()
    },
    // 封装添加函数
    async add() {
      await addRole(this.form)
      // console.log(res)
      // 提示用户
      Message.success('添加成功')
      // 添加成功后跳转到添加数据的那一页
      // 添加成功之后数据还没没喧嚷上,要手动加一
      // 一定要在进行运算前就加一,要不然页码会被覆盖掉,不会变化
      this.total = this.total + 1
      // 再进行总条数 除以 每页条数计数出 页数
      this.page = Math.ceil(this.total / this.pagesize)
      // 重新渲染
      this.getRole()
      // 清空表单/关闭弹窗
      this.hCancel()
    },
    // 添加
    addAffirm() {
      // 兜底校验
      this.$refs.form.validate((val) => {
        if (val) {
          this.add()
        }
      })
    },
    // 取消
    hCancel() {
      this.$refs.form.resetFields() // 重置表单数据
      this.showDialog = false // 关闭弹层
    },
    // 编辑
    hEdit(row) {
      row.isEdit = true
    },
    // 编辑确认
    async editOk(row) {
      if (!row.editRow.name || !row.editRow.description) return Message.error('内容不能为空')
      // 发送请求
      const res = await updateEdit(row.editRow)
      // 提示用户
      Message.success(res.message)
      // 关闭输入框
      // eslint-disable-next-line require-atomic-updates
      row.isEdit = false
      // 更新数据
      this.getRole()
    },
    // 删除
    async del(id) {
      // console.log(id)
      await delRole(id)
      // 提示用户
      Message.success('删除成功')
      // 删除当前页的最后一条数据,要向前进行翻页
      if (this.list.length === 1) {
        if (this.page > 1) this.page--
      }
      // 重新渲染数据
      this.getRole()
    }
  }
}
</script>
<style scoped>
.role-operate {
  padding: 10px;
}
</style>
